<template>
  <div>
    <el-page-header :icon="null" title="用户管理" content="管理系统中的所有用户" />
    
    <!-- 搜索和操作区 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱..."
          prefix-icon="Search"
          @input="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="12">
        <div style="text-align: right;">
          <el-button type="primary" @click="showAddUserModal = true">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
          <el-button @click="refreshUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-select v-model="roleFilter" @change="applyFilters" placeholder="筛选角色" style="width: 120px;">
            <el-option label="全部角色" value="" />
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </div>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-card style="margin-top: 20px;">
      <el-table 
        :data="users" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phoneNumber" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'" size="small">
              {{ row.isActive ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="160">
          <template #default="{ row }">
            {{ formatTime(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewUser(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editUser(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.isActive ? 'warning' : 'success'"
              @click="toggleUserStatus(row)"
            >
              {{ row.isActive ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div v-if="selectedUsers.length > 0" style="margin-top: 15px;">
        <el-alert 
          :title="`已选择 ${selectedUsers.length} 个用户`" 
          type="info" 
          :closable="false"
        >
          <el-button type="danger" size="small" @click="batchDeleteUsers">批量删除</el-button>
          <el-button size="small" @click="batchToggleStatus('disable')">批量禁用</el-button>
          <el-button size="small" @click="batchToggleStatus('enable')">批量启用</el-button>
        </el-alert>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="totalPages > 1"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalUsers"
        layout="prev, pager, next, sizes, total"
        @current-change="changePage"
        style="margin-top: 20px; text-align: center;"
      />
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="showUserModal"
      title="用户详情"
      width="600px"
    >
      <div v-if="selectedUser">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ selectedUser.id }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ selectedUser.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ selectedUser.email }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ selectedUser.phoneNumber || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="getRoleType(selectedUser.role)">
              {{ getRoleText(selectedUser.role) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedUser.isActive ? 'success' : 'danger'">
              {{ selectedUser.isActive ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatTime(selectedUser.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatTime(selectedUser.lastLoginTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">权限信息</el-divider>
        <el-table :data="userPermissions" v-loading="loadingPermissions">
          <el-table-column prop="documentTitle" label="文档名称" />
          <el-table-column prop="action" label="权限" />
          <el-table-column prop="grantedAt" label="授权时间">
            <template #default="{ row }">
              {{ formatTime(row.grantedAt) }}
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!loadingPermissions && userPermissions.length === 0" description="暂无权限信息" />
      </div>
    </el-dialog>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddUserModal"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="editingUser" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" style="width: 100%;">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddUserModal">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="savingUser">
          {{ editingUser ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { userApi } from '@/api'

const users = ref([])
const loading = ref(false)
const searchQuery = ref('')
const roleFilter = ref('')
const selectedUsers = ref([])
const showUserModal = ref(false)
const showAddUserModal = ref(false)
const selectedUser = ref(null)
const userPermissions = ref([])
const loadingPermissions = ref(false)
const editingUser = ref(false)
const savingUser = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const totalUsers = ref(0)

const totalPages = computed(() => Math.ceil(totalUsers.value / pageSize.value))

// 用户表单
const userForm = ref({
  username: '',
  email: '',
  phoneNumber: '',
  password: '',
  role: 'user',
  isActive: true
})

const userFormRef = ref()

const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 处理选中变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection.map(item => item.id)
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const result = await userApi.getAllUsers({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value,
      role: roleFilter.value
    })
    users.value = Array.isArray(result) ? result : (result.data || [])
    totalUsers.value = result.total || users.value.length
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = async () => {
  currentPage.value = 1
  await fetchUsers()
}

// 应用筛选
const applyFilters = async () => {
  currentPage.value = 1
  await fetchUsers()
}

// 查看用户详情
const viewUser = async (user) => {
  selectedUser.value = user
  showUserModal.value = true
  
  // 获取用户权限
  loadingPermissions.value = true
  try {
    const permissions = await userApi.getUserPermissions(user.id)
    userPermissions.value = Array.isArray(permissions) ? permissions : (permissions.data || [])
  } catch (error) {
    console.error('获取用户权限失败:', error)
    userPermissions.value = []
  } finally {
    loadingPermissions.value = false
  }
}

// 编辑用户
const editUser = (user) => {
  editingUser.value = true
  userForm.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    phoneNumber: user.phoneNumber || '',
    role: user.role,
    isActive: user.isActive
  }
  showAddUserModal.value = true
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.isActive ? '禁用' : '启用'}用户 "${user.username}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userApi.updateUserStatus(user.id, !user.isActive)
    await fetchUsers()
    ElMessage.success(`用户${user.isActive ? '禁用' : '启用'}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error('更新用户状态失败')
    }
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await userApi.deleteUser(userId)
    await fetchUsers()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 批量删除用户
const batchDeleteUsers = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const userId of selectedUsers.value) {
      await userApi.deleteUser(userId)
    }
    selectedUsers.value = []
    await fetchUsers()
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量切换状态
const batchToggleStatus = async (action) => {
  try {
    const isDisable = action === 'disable'
    await ElMessageBox.confirm(
      `确定要${isDisable ? '禁用' : '启用'}选中的 ${selectedUsers.value.length} 个用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    for (const userId of selectedUsers.value) {
      await userApi.updateUserStatus(userId, !isDisable)
    }
    selectedUsers.value = []
    await fetchUsers()
    ElMessage.success(`批量${isDisable ? '禁用' : '启用'}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`批量${action}失败:`, error)
      ElMessage.error(`批量${action}失败`)
    }
  }
}

// 保存用户
const saveUser = async () => {
  try {
    const valid = await userFormRef.value.validate()
    if (!valid) return

    savingUser.value = true
    
    if (editingUser.value) {
      await userApi.updateUser(userForm.value.id, userForm.value)
      ElMessage.success('用户更新成功')
    } else {
      await userApi.createUser(userForm.value)
      ElMessage.success('用户创建成功')
    }
    
    closeAddUserModal()
    await fetchUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  } finally {
    savingUser.value = false
  }
}

// 关闭用户详情对话框
const closeUserModal = () => {
  showUserModal.value = false
  selectedUser.value = null
  userPermissions.value = []
}

// 关闭添加用户对话框
const closeAddUserModal = () => {
  showAddUserModal.value = false
  editingUser.value = false
  userFormRef.value?.resetFields()
  userForm.value = {
    username: '',
    email: '',
    phoneNumber: '',
    password: '',
    role: 'user',
    isActive: true
  }
}

// 刷新用户列表
const refreshUsers = () => {
  searchQuery.value = ''
  roleFilter.value = ''
  selectedUsers.value = []
  currentPage.value = 1
  fetchUsers()
}

// 换页
const changePage = (page) => {
  currentPage.value = page
  fetchUsers()
}

// 工具函数
const getRoleType = (role) => {
  const typeMap = {
    admin: 'danger',
    user: 'primary'
  }
  return typeMap[role] || 'info'
}

const getRoleText = (role) => {
  const roleMap = {
    admin: '管理员',
    user: '普通用户'
  }
  return roleMap[role] || role
}

const formatTime = (time) => {
  if (!time) return '无'
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchUsers()
})
</script>
